package com.yfp.operation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yfp.common.security.utils.SecurityUtils;
import com.yfp.operation.domain.AiModelConfig;
import com.yfp.operation.domain.dto.AiModelConfigDTO;
import com.yfp.operation.domain.dto.AiModelServiceInfoDTO;
import com.yfp.operation.domain.dto.SiliconFlowRetrieveModelsInformationDTO;
import com.yfp.operation.domain.vo.AiModelConfigVO;
import com.yfp.operation.mapper.AiModelConfigMapper;
import com.yfp.operation.service.AiModelConfigService;
import com.yfp.operation.service.SiliconFlowService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;

/**
 *
 * @description 针对表【ai_model_config(AI模型配置表)】的数据库操作Service实现
 * @createDate 2025-02-24 15:08:52
 */
@Service
public class AiModelConfigServiceImpl extends ServiceImpl<AiModelConfigMapper, AiModelConfig> implements AiModelConfigService {

    @Resource
    private SiliconFlowService siliconFlowService;
    @Resource
    private AiModelConfigMapper aiModelConfigMapper;

    @Override
    public List<AiModelConfig> listByModelServiceId(Long aiModelServiceId) {
        return aiModelConfigMapper.selectByModelServiceId(aiModelServiceId);
    }

    @Override
    public void removeByModelServiceId(Long aiModelServiceId) {
        aiModelConfigMapper.removeByModelServiceId(aiModelServiceId);
    }

    @Override
    public List<AiModelConfigVO> searchModelServiceInfoBySiliconFlow(AiModelServiceInfoDTO aiModelServiceInfoDTO) {
        Assert.notBlank(aiModelServiceInfoDTO.getApiUrl(), "API 地址不能为空");
        Assert.notBlank(aiModelServiceInfoDTO.getApiKey(), "API 密钥不能为空");

        aiModelServiceInfoDTO.setType("silicon-flow");
        // 目前只对接 silicon-flow 硅基流动
        if (StrUtil.equals(aiModelServiceInfoDTO.getType(), "silicon-flow")) {
            SiliconFlowRetrieveModelsInformationDTO retrieveModelsInformationDTO = siliconFlowService.retrieveModelsInformation(aiModelServiceInfoDTO);
            AtomicLong atomicLong = new AtomicLong(1);
            List<AiModelConfigVO> SiliconFlowModelList = retrieveModelsInformationDTO.getData().stream().filter(item -> {
                String name = Optional.ofNullable(CollUtil.getFirst(aiModelServiceInfoDTO.getAiModelConfigs())).map(AiModelConfigDTO::getName).orElse(null);
                if (StrUtil.isBlank(name)) {
                    return true;
                } else {
                    return StrUtil.containsIgnoreCase(item.getId(), name);
                }
            }).map(item -> {
                AiModelConfigVO aiModelConfigVO = new AiModelConfigVO();
                aiModelConfigVO.setId(atomicLong.getAndIncrement());
                aiModelConfigVO.setName(item.getId());
                return aiModelConfigVO;
            }).toList();
            return SiliconFlowModelList;
        }
        return List.of();
    }

    @Override
    public AiModelConfigVO searchConfigServiceInfo(Long id) {
        AiModelConfig aiModelConfig = aiModelConfigMapper.selectById(id);
        AiModelConfigVO aiModelConfigVO = BeanUtil.toBean(aiModelConfig, AiModelConfigVO.class);

        return aiModelConfigVO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateConfigServiceInfo(AiModelConfigDTO aiModelConfigDTO) {
        AiModelConfig aiModelConfig = BeanUtil.toBean(aiModelConfigDTO, AiModelConfig.class);

        // 将其他模型是否为默认，取消掉
        this.cancelDefaultModel(aiModelConfigDTO);

        // 更新
        DateTime date = DateUtil.date();
        Long userId = SecurityUtils.getUserId();

        aiModelConfig.setUpdateTime(date);
        aiModelConfig.setUpdateUserId(userId);

        aiModelConfigMapper.updateById(aiModelConfig);
    }

    @Override
    public List<AiModelConfigVO> searchModelServiceInfoList(AiModelConfigDTO aiModelConfigDTO) {
        LambdaQueryWrapper<AiModelConfig> query = Wrappers.lambdaQuery();
        query.like(StrUtil.isNotBlank(aiModelConfigDTO.getName()), AiModelConfig::getName, aiModelConfigDTO.getName());

        List<AiModelConfig> aiModelConfigs = aiModelConfigMapper.selectList(query);
        List<AiModelConfigVO> aiModelConfigVOS = BeanUtil.copyToList(aiModelConfigs, AiModelConfigVO.class);

        return aiModelConfigVOS;
    }

    @Override
    public void cancelDefaultModel(AiModelConfigDTO aiModelConfigDTO) {
        AiModelConfig aiModelConfig = aiModelConfigMapper.selectById(aiModelConfigDTO.getId());
        if (Objects.isNull(aiModelConfig)){
            return;
        }

        DateTime date = DateUtil.date();
        Long userId = SecurityUtils.getUserId();

        AiModelConfig tempAiModelConfig = new AiModelConfig();
        tempAiModelConfig.setAiModelServiceId(aiModelConfigDTO.getId());
        tempAiModelConfig.setUpdateTime(date);
        tempAiModelConfig.setUpdateUserId(userId);
        aiModelConfigMapper.cancelDefaultModel(tempAiModelConfig);
    }

}




